package com.ciwong.epaper.modules.scan.ui;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.hardware.Camera;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Handler;
import android.os.PowerManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.bean.SelectObject;
import com.ciwong.epaper.modules.epaper.bean.Answer;
import com.ciwong.epaper.modules.epaper.bean.Module;
import com.ciwong.epaper.modules.epaper.bean.ModuleContent;
import com.ciwong.epaper.modules.epaper.bean.ModuleInfo;
import com.ciwong.epaper.modules.me.bean.Clazz;
import com.ciwong.epaper.modules.me.util.MeJumpManager;
import com.ciwong.epaper.modules.scan.adapter.BaseAdapter;
import com.ciwong.epaper.modules.scan.bean.HomeWorkCommitInfo;
import com.ciwong.epaper.modules.scan.dao.ScanAction;
import com.ciwong.epaper.modules.scan.dao.ScanDao;
import com.ciwong.epaper.modules.scan.event.CloseActivityEvent;
import com.ciwong.epaper.modules.scan.event.CommitHomeWorkEvent;
import com.ciwong.epaper.modules.scan.util.ScanHandler;
import com.ciwong.epaper.modules.scan.util.ScanJumpManager;
import com.ciwong.epaper.modules.scan.util.TextPaperEditChangedListener;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.IntentValue;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.epaper.util.download.DownLoadInfo;
import com.ciwong.eventbus.EventBus;
import com.ciwong.libs.audio.play.AudioPlayer;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.DeviceUtils;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.libs.widget.CWToast;
import com.ciwong.mobilelib.application.BaseApplication;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.i.ViewOnClickListener;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.BaseJumpManager;
import com.ciwong.mobilelib.utils.BaseUtils;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.ciwong.mobilelib.widget.CWDialog;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import com.zxing.camera.CameraManager;
import com.zxing.camera.SaveBitmap;
import com.zxing.decoding.CaptureActivityHandler;
import com.zxing.decoding.InactivityTimer;
import com.zxing.i.ZXingInterface;
import com.zxing.view.ViewfinderView;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

/**
 * 二维码 扫描界面
 */
public class CaptureActivity extends BaseActivity implements SurfaceHolder.Callback, ZXingInterface, DialogInterface.OnDismissListener {

    private static final int NEXT_TIME = 3000;

    private static final int SCAN_NOT_FOUND_TIME = 10000;

    public static final String INTENT_FLAG_ANSWER = "intent_flag_answer";


    private final String TAG = tag;

    private ViewfinderView mViewfinderView;

    private boolean mHasSurface;

    private InactivityTimer mInactivityTimer;

    private PowerManager.WakeLock mWakeLock;

    private CaptureActivityHandler mHandler;

    private String mCharacterSet;

    private Vector<BarcodeFormat> mDecodeFormats;

    private boolean mPlayBeep;

    private boolean mVibrate;

    private ScanHandler mScanHandler;

    private ScanHandler.HomeWorkData mHomeWorkData;

    private ProgressDialog mProgressDialog;

    private String mAnswerCardTip = "";

    private String mQrCardTip = "";

    private ViewGroup viewTopLayout, viewBottomLayout;

    private TextView mTvTitle;

    private Gallery mGalleyTab;

    private int height = 0;

    private int width = 0;

    private int currentSelectPos = 0;

    private int[] mImgIds = new int[]{R.drawable.btn_scan_qrcode_selector,
    };

    private List<ImageView> mImageViews = new ArrayList<ImageView>();

    private CameraManager mCameraManager;

    private boolean mIsLoadClassList = false;

    private List<Clazz> mClazzList;

    private TextView tvSelectClass;

    private boolean isOutAnswer = false;

    private boolean online;


    private ViewOnClickListener mViewOnClickListener = new ViewOnClickListener() {
        @Override
        public void avertRepeatOnClick(View v) {
            int id = v.getId();
            if (id == R.id.btn_close) {
                finish();
            }
        }
    };

    @Override
    protected int setView() {
        return R.layout.activity_capture;
    }

    @Override
    protected void findViews() {
        viewTopLayout = (ViewGroup) findViewById(R.id.top_layout);
        viewBottomLayout = (ViewGroup) findViewById(R.id.bottom_layout);
        mViewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
        mGalleyTab = (Gallery) findViewById(R.id.bottom_vp);
        mTvTitle = (TextView) findViewById(R.id.tv_title);
        mHasSurface = false;
        mInactivityTimer = new InactivityTimer(this);
        mWakeLock = ((PowerManager) getSystemService(POWER_SERVICE))
                .newWakeLock(
                        PowerManager.SCREEN_BRIGHT_WAKE_LOCK
                                | PowerManager.ON_AFTER_RELEASE,
                        getPackageName());
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setMessage(getString(R.string.sao_loading));
        mProgressDialog.setCanceledOnTouchOutside(false);
        mViewfinderView.setTopText("将纸质报纸上的二维码放入扫描框内,即可自动识别电子报品牌");
    }

    @Override
    protected void initEvent() {
        EventBus.getDefault().register(this);
        findViewById(R.id.btn_close).setOnClickListener(mViewOnClickListener);
        GalleryEvent galleryEvent = new GalleryEvent();
        mGalleyTab.setOnItemClickListener(galleryEvent);
        mGalleyTab.setOnItemSelectedListener(galleryEvent);
    }

    @Override
    protected void init() {
//        StatUtils.statVisits(StatUtils.Operation.OPERATION_TYPE_SCAN);
        hideTitleBar();
        mCameraManager = CameraManager.init(getApplication());
        if (mCameraManager
                .getCurrentCaptureMode() == CameraManager.CaptureMode.ANSWERCARD) {
            mViewfinderView.stopScanAnim();
        }
        Intent in = getIntent();
        int mode = in.getIntExtra(IntentFlag.INTENT_FLAG_TYPE,
                CameraManager.CaptureMode.DEFAULT);
        mCameraManager.setCaptureMode(mode);
        mScanHandler = ScanHandler.me();
        mHomeWorkData = mScanHandler.getHomeWorkData();
        mScanHandler.preparedoNewHomeWork();

        mAnswerCardTip = getString(R.string.answer_card_tip);
        mQrCardTip = getString(R.string.qr_card_tip);

        width = height = DeviceUtils.dip2px(35);

        try {
            Answer answer = (Answer) in
                    .getSerializableExtra(INTENT_FLAG_ANSWER);
            if (answer != null) {
                isOutAnswer = true;
            }
            mHomeWorkData.setAnswerData(answer);
        } catch (Exception e) {
            e.printStackTrace();
        }
        initData();
        mGalleyTab.setSpacing(20);
        mGalleyTab.setAnimation(
                AnimationUtils.loadAnimation(this, R.anim.scan_tab_in));
        mGalleyTab.setAdapter(new BaseAdapter<ImageView>(mImageViews) {
            @Override
            public View getView(int position, View convertView,
                                ViewGroup parent) {
                ImageView iv = mImageViews.get(position);
                Gallery.LayoutParams lp = (Gallery.LayoutParams) iv
                        .getLayoutParams();
                if (position != currentSelectPos) {
                    lp.width = width;
                    lp.height = height;
                    iv.setLayoutParams(lp);
                } else {
                    lp.width = width * 2;
                    lp.height = height * 2;
                    iv.setLayoutParams(lp);
                }
                return iv;
            }
        });
        updateMode();
        online = NetworkUtils.isOnline();
        IntentFilter filter = new IntentFilter();
        filter.addAction(CONNECTIVITY_CHANGE_ACTION);
        registerReceiver(receiver, filter);
        isCancelToastOnPause = false;
    }

    public static final String CONNECTIVITY_CHANGE_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";


    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(CONNECTIVITY_CHANGE_ACTION)) {
                online = NetworkUtils.isOnline();
                if (online) {
                    mViewfinderView.startScanAnim();
                    mCameraManager.setNeedUseZxingScan(true);
                    mViewfinderView.setText(getString(R.string.qr_card_tip));
                } else {
                    mViewfinderView.stopScanAnim();
                    mCameraManager.setNeedUseZxingScan(false);
                    mViewfinderView.setText(getString(R.string.connect_disable));
                }
            }
        }
    };


    @Override
    protected void loadData() {
        getLocalClassList();
    }

    @Override
    protected void onResume() {
        super.onResume();
        SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
        SurfaceHolder surfaceHolder = surfaceView.getHolder();
        if (mHasSurface) {
            initCamera(surfaceHolder, 0, 0);
        } else {
            surfaceHolder.addCallback(this);
            surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }
        mDecodeFormats = null;
        mCharacterSet = null;

        mPlayBeep = true;
        AudioManager audioService = (AudioManager) getSystemService(
                AUDIO_SERVICE);
        if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
            mPlayBeep = false;
        }
        // initBeepSound();
        mVibrate = true;
        mWakeLock.acquire();
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mHandler != null) {
            mHandler.quitSynchronously();
            mHandler = null;
        }
        mCameraManager.closeDriver();
        mWakeLock.release();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mInactivityTimer.shutdown();
        EventBus.getDefault().unregister(this);
        mScanHandler.preparedoNewHomeWork();
        mScanHandler.doBatchHomeWorkEnd();
        AudioPlayer.getInstance().release();
        //解除广播
        if (receiver != null) {
            unregisterReceiver(receiver);
        }
    }

    private void getLocalClassList() {
        SerializableManager.getInstance().deSerialize(
                SerializableManager.SerializeKey.SHARE_KEY_CLASS_LIST,
                new BaseCallBack() {


                    @Override
                    public void success(Object data) {
                        mIsLoadClassList = true;
                        mClazzList = (List<Clazz>) data;

                    }

                    @Override
                    public void failed(int errorCode, Object data) {
                        mIsLoadClassList = true;
                    }

                    @Override
                    public void failed(Object data) {
                        mIsLoadClassList = true;
                    }
                });
    }

    private class GalleryEvent implements AdapterView.OnItemSelectedListener,
            AdapterView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            onEvent(parent, view, position, id);
        }

        @Override
        public void onItemSelected(AdapterView<?> parent, View view,
                                   final int position, long id) {
            onEvent(parent, view, position, id);
            if (position == 1) {
                mCameraManager.setNeedUseZxingScan(false);
                if (mHandler != null) {
                    mHandler.sendEmptyMessageDelayed(R.id.decode_failed, 20);
                }
                if (!isOutAnswer) {
                    doSelectAnswerCardTab();
                }
            } else {
                //加一个网络判断
                if (online) {
                    mViewfinderView.startScanAnim();
                    mCameraManager.setNeedUseZxingScan(true);
                } else {
                    mViewfinderView.stopScanAnim();
                    mCameraManager.setNeedUseZxingScan(false);
                    mViewfinderView.setText(getString(R.string.connect_disable));
                }

            }
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    mGalleyTab.setSelection(position);
                }
            }, 200);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }

        private void onEvent(AdapterView<?> parent, View view, int position,
                             long id) {
            currentSelectPos = position;
            BaseAdapter adapter = (BaseAdapter) mGalleyTab.getAdapter();
            adapter.notifyDataSetChanged();
            if (position == 0) {
                mTvTitle.setText(R.string.sao_qrcode);
                switchMode(CameraManager.CaptureMode.QRCODE);
                updateMode();
            } else {
                int currentMode = mCameraManager.getCurrentCaptureMode();
                if (currentMode == CameraManager.CaptureMode.QRCODE) {
                    if (mHandler != null) {
                        mHandler.sendEmptyMessage(R.id.decode_failed);
                    }
                    mHomeWorkData.clear();
                    // showAddCodeDialog();
                } // 扫答题卡
                mTvTitle.setVisibility(View.VISIBLE);
                mTvTitle.setText(R.string.sao_answer_card);
                switchMode(CameraManager.CaptureMode.ANSWERCARD);
                updateMode();

            }
        }
    }

    private void doSelectAnswerCardTab() {
        if (online) {
            EApplication application = (EApplication) getApplication();
            Clazz clazz = application.getClazz();
            if (clazz != null) // 有网络有班级
            {
                if (mIsLoadClassList) {
                    mScanHandler.getHomeWorkData().setClazz(clazz);
                    int clssListSize = 0;
                    if (mClazzList != null) {
                        clssListSize = mClazzList.size();
                    }
                    if (clssListSize > 1) {
                        // 多个班级
                        showAddCodeDialog(true, clazz.getClassName());
                    } else if (clssListSize == 1) {
                        // 单个班级
                        showAddCodeDialog(false, clazz.getClassName());
                    } else {
                        showConfirmAddClassDialog();
                    }
                } else {
                    Toast.makeText(CaptureActivity.this, "班级列表正在加载中,请稍后进入",
                            Toast.LENGTH_LONG).show();
                }
            } else {
                showConfirmAddClassDialog();
            }

        } else
        // 无网络
        {
            mViewfinderView.setText(getString(R.string.connect_disable));
            mViewfinderView.stopScanAnim();
        }
    }

    /**
     * 未加入班级提示框
     */
    private void showConfirmAddClassDialog() {
        CWDialog dialog = new CWDialog(this, false, false);
        dialog.setMessage(R.string.no_add_class_tip);
        dialog.setCancelable(true);
        dialog.setPositiveButton(getString(R.string.add_class),
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mGalleyTab.setSelection(0);
                        mTvTitle.setText(R.string.sao_qrcode);
                        MeJumpManager.jumpToJoinClassActivity(R.string.go_back,
                                CaptureActivity.this,
                                IntentValue.JumpToJoinClassType.FROM_CLASS_LIST,
                                0);
                        dialog.dismiss();
                        finish();
                    }
                }, false).setNegativeButton(getString(R.string.cancel),
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog,
                                        int which) {
                        mGalleyTab.setSelection(0);
                        mTvTitle.setText(R.string.sao_qrcode);
                    }
                })
                .show();
    }

    private void initData() {
        ImageTabClick imageTabClick = new ImageTabClick();
        int index = 0;
        mGalleyTab.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
        for (int imgId : mImgIds) {
            final ImageView imageView = new ImageView(getApplicationContext());
            Gallery.LayoutParams params = new Gallery.LayoutParams(width,
                    height);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setImageResource(imgId);
            imageView.setLayoutParams(params);
            imageView.setFocusable(true);
            imageView.setFocusableInTouchMode(true);
            imageView.setEnabled(true);
            imageView.setClickable(true);
            imageView.setTag(index);
            imageView.setOnClickListener(imageTabClick);
            mImageViews.add(imageView);
            index++;
        }
    }

    /**
     * 开始拍照
     */
    private void doTackPic() {
        if (!isOutAnswer && !online) {
            return;
        }
        byte[] yuvData = mCameraManager.getCurrentData();
        int answercardSize = mScanHandler.getAnswercardSize();
        if (yuvData == null && answercardSize < 2) {
            return;
        }
        CWLog.d(TAG, "开始拍照");

        Camera camera = mCameraManager.getCamera();
        ByteArrayOutputStream filecon = null;
        try {
            Camera.Parameters parameters = camera.getParameters();
            Camera.Size size = parameters.getPreviewSize();
            YuvImage image = new YuvImage(yuvData,
                    parameters.getPreviewFormat(), size.width, size.height,
                    null);
            filecon = new ByteArrayOutputStream(1024);
            image.compressToJpeg(
                    new Rect(0, 0, image.getWidth(), image.getHeight()), 70,
                    filecon);
            byte[] data = filecon.toByteArray();
            Bitmap bitmap = SaveBitmap.adjustPhotoRotation(data, 90);
            Result result = new Result(null, null, null,
                    BarcodeFormat.AZTEC);
            handleDecode(result, bitmap);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (filecon != null) {
                try {
                    filecon.flush();
                    filecon.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
    }

    class ImageTabClick implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            int position = (Integer) v.getTag();
            if (position == 1 && mGalleyTab.getSelectedItemPosition() == 1) {
                doTackPic();
            } else {

            }
            startAnimation(position);
            mGalleyTab.setSelection(position);
        }
    }

    public void startAnimation(int selection) {
        int currentSelect = mGalleyTab.getSelectedItemPosition();
        if (selection != currentSelect) {
            Animation inAnimation = AnimationUtils.loadAnimation(this,
                    R.anim.scan_tab_in);
            Animation outAnimation = AnimationUtils.loadAnimation(this,
                    R.anim.scan_tab_out);
            ImageView Left = (ImageView) mGalleyTab.getChildAt(0);
            ImageView right = (ImageView) mGalleyTab.getChildAt(1);

            if (selection == 0) {
                Left.startAnimation(outAnimation);
                right.startAnimation(inAnimation);
            } else if (selection == 1) {
                Left.startAnimation(inAnimation);
                right.startAnimation(outAnimation);
            }
        }
    }

    private void updateMode() {
        int currentMode = mCameraManager.getCurrentCaptureMode();
        if (currentMode == CameraManager.CaptureMode.ANSWERCARD) {
            mTvTitle.setVisibility(View.VISIBLE);
            mTvTitle.setText(R.string.sao_answer_card);
            mViewfinderView.setText(mAnswerCardTip);
            findViewById(R.id.tv_slect_brand_tip).setVisibility(View.INVISIBLE);
            findViewById(R.id.tv_select_brand).setVisibility(View.INVISIBLE);
            mGalleyTab.setSelection(1);
        } else if (CameraManager.CaptureMode.NEWSPAPER_BRAND == currentMode) {
            viewBottomLayout.setVisibility(View.GONE);
            mTvTitle.setVisibility(View.VISIBLE);
            mTvTitle.setText(R.string.select_ele_brand);
            findViewById(R.id.tv_slect_brand_tip).setVisibility(View.VISIBLE);
            findViewById(R.id.tv_select_brand).setVisibility(View.VISIBLE);

        } else {
            mTvTitle.setVisibility(View.VISIBLE);
            mTvTitle.setText(R.string.sao_qrcode);
            mViewfinderView.setText(mQrCardTip);
            findViewById(R.id.tv_slect_brand_tip).setVisibility(View.INVISIBLE);
            findViewById(R.id.tv_select_brand).setVisibility(View.INVISIBLE);
        }
    }

    public void onEventMainThread(CommitHomeWorkEvent item) {
        commitHomeWork(item);
    }

    public void onEventMainThread(CloseActivityEvent closeEvent) {
        finish();
    }

    private void commitHomeWork(final CommitHomeWorkEvent item) {
        try {
            if (!mScanHandler.hasAnswerCard()) {
                CWToast.makeText(this, "还没有扫码", Toast.LENGTH_LONG, true)
                        .setToastType(CWToast.TOAST_TYPE_ALERT).show();
                return;
            }
            long uid = ((BaseApplication) getApplication()).getUserInfoBase()
                    .getUserId();

            Intent intent = this.getIntent();
            Answer answer = new Answer();
            answer.setCodeId(mHomeWorkData.getCodeId());
            answer.setClassId(
                    String.valueOf(mHomeWorkData.getClazz().getClassId()));
            DownLoadInfo mDownLoadInfo = (DownLoadInfo) intent
                    .getSerializableExtra(IntentFlag.INTENT_FLAG_DOWNLOAD_INFO);
            Module mModule = (Module) intent
                    .getSerializableExtra(IntentFlag.INTENT_FLAG_OBJ);
            int position = intent.getIntExtra(IntentFlag.INTENT_FLAG_POSITION,
                    0);
            if (mModule == null) {
                mModule = new Module();
                ModuleInfo moduleInfo = new ModuleInfo();
                moduleInfo.setModuleId(ModuleInfo.ModuleInfoId.MODULE_ID_TEST);
                List<ModuleContent> moduleContentList = new ArrayList<ModuleContent>();
                ModuleContent moduleContent = new ModuleContent();
                moduleContent.setResourceType(
                        ModuleContent.ResourceType.RESOURCE_TYPE_TEST);
                moduleContent.setResourceName("单元测试");
                moduleContentList.add(moduleContent);
                mModule.setModuleInfo(moduleInfo);
                mModule.setResourceList(moduleContentList);
            }
            HomeWorkCommitInfo homeWorkCommitInfo = new HomeWorkCommitInfo();
            homeWorkCommitInfo.setAnswer(answer);
            homeWorkCommitInfo.setmDownLoadInfo(mDownLoadInfo);
            homeWorkCommitInfo.setmModule(mModule);
            homeWorkCommitInfo.setPosition(position);
            homeWorkCommitInfo.setUserId(uid);
            mScanHandler.commitHomework(homeWorkCommitInfo, new BaseExtCallBack(CaptureActivity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {

                @Override
                public void success() {
                    if (item.isSubmitWork()) {
                        showSubmitingDialog();
                    }
                }

                @Override
                public void failed(int errorCode, Object data) {
                    super.failed(errorCode, data);
                    showToastError(errorCode, data);

                }

                @Override
                public void failed(Object data) {
                    CWToast.makeText(CaptureActivity.this,
                            R.string.submit_work_fail, CWToast.LENGTH_LONG,
                            true).setToastType(CWToast.TOAST_TYPE_ERROR).show();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 展示提交框
     */
    private void showSubmitingDialog() {
        CWDialog dialog = new CWDialog(this);
        stopCamera();
        dialog.setMessage(R.string.submit_work_success);
        dialog.setCancelable(true);
        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                finish();
            }
        });
        dialog.setPositiveButton(R.string.look_detail,
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                        MeJumpManager.jumpToStudyRecord(0, CaptureActivity.this,
                                R.string.go_back, 0);
                    }
                }).setNegativeButton(R.string.i_know,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog,
                                        int which) {
                        finish();
                    }
                })
                .show();
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        try {
            CameraManager.viewTopLayoutHeight = viewTopLayout.getHeight();
            CameraManager.viewBottomLayoutHeight = viewBottomLayout.getHeight();

            int[] titleText = new int[2];
            mTvTitle.getLocationInWindow(titleText);

            TextView viewTip = (TextView) findViewById(R.id.tv_slect_brand_tip);
            int space = DeviceUtils.dip2px(18);
            CameraManager cameraManager = mCameraManager;
            Rect r = cameraManager.getFramingRect();

            Rect tipRect = new Rect(space, titleText[1] + mTvTitle.getHeight(),
                    DeviceUtils.getScreenWdith() - space,
                    r == null ? 0 : r.top);
            ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) viewTip
                    .getLayoutParams();
            layoutParams.height = tipRect.height();
            layoutParams.topMargin = tipRect.top;
            viewTip.setText(R.string.select_ele_brand_tip);
            viewTip.setLayoutParams(layoutParams);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showNoCameraPermission() {
        CWToast.makeText(CaptureActivity.this, R.string.no_camera_permission,
                CWToast.LENGTH_LONG, true)
                .setToastType(CWToast.TOAST_TYPE_ERROR).show();
    }

    private void initCamera(SurfaceHolder surfaceHolder, int width, int height) {
        try {
            mCameraManager.openDriver(surfaceHolder, width, height);
        } catch (IOException ioe) {
            ioe.printStackTrace();
            showNoCameraPermission();
            return;
        } catch (RuntimeException e) {
            e.printStackTrace();
            showNoCameraPermission();
            return;
        }
        if (mHandler == null) {
            mHandler = new CaptureActivityHandler(this, mDecodeFormats,
                    mCharacterSet, this);
        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder surfaceHolder) {
        if (!mHasSurface) {
            mHasSurface = true;
            initCamera(surfaceHolder, 0, 0);
        }

    }

    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int format,
                               int width, int height) {


    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
        mHasSurface = false;
        //在本类onresume() 时已经处理了 mHandler.quitSynchronously();
        /*if ( mCameraManager.getCamera() != null) {
            if ( mCameraManager.getCamera() != null && mCameraManager.isPreviewing()) {
                if (!mCameraManager.isUseOneShotPreviewCallback()) {
                    mCameraManager.getCamera().setPreviewCallback(null);
                }
                mCameraManager.getCamera().stopPreview();
                mCameraManager.getPreviewCallback().setHandler(null, 0);
                mCameraManager.getAutoFocusCallback().setHandler(null, 0);
                mCameraManager.setPreviewing(false);
            }
        }*/

    }

    @Override
    public ViewfinderView getViewfinderView() {
        return mViewfinderView;
    }

    @Override
    public Handler getHandler() {
        return mHandler;
    }

    @Override
    public void drawViewfinder() {
        mViewfinderView.drawViewfinder();
    }

    @Override
    public void handleDecode(Result result, Bitmap barcode) {
        int currentMode = mCameraManager.getCurrentCaptureMode();

        if (result.getBarcodeFormat() == BarcodeFormat.AZTEC
                && currentMode == CameraManager.CaptureMode.ANSWERCARD) {
            if (currentMode == CameraManager.CaptureMode.QRCODE) {
                releaseBitmap(barcode);
                if (mHandler != null) {
                    mHandler.sendEmptyMessage(R.id.restart_preview);
                }
                return;
            }
            boolean saveIsSuc = mScanHandler.saveAnswerCard(barcode, result);

            AudioPlayer.getInstance().play(R.raw.answer_card_beep, this, null);
            if (saveIsSuc && mScanHandler.getAnswercardSize() == 2) {
                ScanJumpManager.jumpAnswerCard(this,
                        mScanHandler.getAnswerCard(),
                        mScanHandler.getAnswerCardSavePath(), isOutAnswer);
                releaseBitmap(barcode);
                return;
            }

            CWToast.makeText(this, R.string.scan_next_tip, Toast.LENGTH_LONG,
                    true).setToastType(CWToast.TOAST_TYPE_SUC).show();

            startCheckTip(SCAN_NOT_FOUND_TIME + NEXT_TIME);
            if (mHandler != null) {
                mHandler.sendEmptyMessageDelayed(R.id.restart_preview,
                        NEXT_TIME);
            }
        } else {
            if (currentMode == CameraManager.CaptureMode.ANSWERCARD) {
                releaseBitmap(barcode);
                return;
            }
            String resultStr = result.getText();
            handQrCode(resultStr);
        }
        releaseBitmap(barcode);
    }

    private void handQrCode(String resultStr) {
        Log.e("qrCode content is : ", resultStr);
        AudioPlayer.getInstance().play(R.raw.beep, this, null);
        try {
            if (TextUtils.isEmpty(resultStr)) {
                ToastUtil.INSTANCE.toastCenter(EApplication.getInstance().getApplicationContext(), R.string.scan_not_support, R.mipmap.ic_error);
                if (mHandler != null) {
                    mHandler.sendEmptyMessageDelayed(R.id.restart_preview, 800);
                }
                return;
            }
            URL url = null;
            String host = null;
            try {
                url = new URL(resultStr);
                host = url.getHost();
            } catch (Exception e) {
                e.printStackTrace();
            }
            switch (mCameraManager.getCurrentCaptureMode()) {
                case CameraManager.CaptureMode.NEWSPAPER_BRAND://扫品牌逻辑  已删除
                    return;
                default://扫一扫  扫码逻辑 资源包是章节的形式的逻辑
                    CWLog.d("Scan", resultStr);
                    if (resultStr.startsWith("http://ew.ciwong.com/qr")) {
                        Log.i("qrCode content is : ", resultStr);
                        //书籍信息单独接口分支
                        if (resultStr.startsWith("http://ew.ciwong.com/qr/book")) {
                            int index = resultStr.lastIndexOf("/");
                            String lasturl = resultStr.substring(index + 1);
                            int producted;
                            //producted为空
                            try {
                                producted = Integer.valueOf(lasturl);
                            } catch (Exception e) {
                                producted = 0;
                            }
                            if (producted == 0) {
                                //直接跳到无相关资源页面
                                ScanJumpManager.jumpNewspaperQRInfo(R.string.go_back, CaptureActivity.this, null, resultStr, true, null);
                            } else {
                                //获取书籍信息
                                ScanDao.getInstance().getBookInfo(CaptureActivity.this, producted + "");
                            }
                        } else if (resultStr.startsWith("http://ew.ciwong.com/qr/preview")) { //资源预览

                            ScanDao.getInstance().newspaperQRInfoLogicPreView(
                                    CaptureActivity.this, resultStr);
                        } else {
                            //原来逻辑
                            Log.i(" resultStr else:", resultStr);
                            ScanDao.getInstance().newspaperQRInfoLogic(
                                    CaptureActivity.this, resultStr);
                        }
                        Log.i(" resultStr.startsWith:", resultStr);
                        return;
                    }
                    Log.i("resultStr.startsWithre:", resultStr);
                    break;
            }
            if (url != null && host != null && !TextUtils.isEmpty(host)
                    && host.contains("qr.ciwong.com")) {
                Log.i("host.contains:", resultStr);
                String path = url.getPath();
                String action = resultStr /* + ownApp + appId */;
                jumpToWebview(action);

            } else if (resultStr.contains(ScanAction.ACTION_JUMP_URL)) {
                Log.i("ScanAcACTION_JUMP_URL:", resultStr);
                jumpToWebview(resultStr);
            } else if (BaseUtils.isNetUrl(resultStr)) {
                Log.i("host:", host);
                Log.i("BaseUtils.isNetUrl:", resultStr);
                //jumpToWebview(resultStr);
                ToastUtil.INSTANCE.toastInCenter(getApplicationContext(), "该域名不合法，可能存在风险！", Toast.LENGTH_LONG);
            } else {
                ToastUtil.INSTANCE.toastInCenter(getApplicationContext(), resultStr, Toast.LENGTH_LONG);
               /* ScanUtil.alertSingleBtnDialog(this, R.string.tips, resultStr,
                        android.R.string.ok, new ScanUtil.CallBack() {
                            @Override
                            public void callback() {
                                finish();
                            }
                        });*/
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            finish();
        }
    }


    private void releaseBitmap(Bitmap bitmap) {
        if (bitmap != null && !bitmap.isRecycled()) {
            bitmap.recycle();
        }
    }

    private void startCheckTip(int time) {
    }


    private void jumpToWebview(String url) {
        BaseJumpManager.jumpToBrowser(this, R.string.go_back, url,
                null);
    }


    /**
     * 切换模式
     *
     * @param mode {@link CameraManager.CaptureMode}
     */
    private void switchMode(int mode) {
        // 二维码
        mCameraManager.setCaptureMode(mode);

        mViewfinderView.updateLineTop();
        if (mode == CameraManager.CaptureMode.ANSWERCARD) {
            mViewfinderView.setText(mAnswerCardTip);
        } else {
            mViewfinderView.setText(mQrCardTip);
        }
        if (mHandler != null) {
            mHandler.sendEmptyMessage(R.id.restart_preview);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode,
                                    Intent data) {
        if (resultCode == RESULT_OK) {
            if (data != null) {
                boolean isFinish = data
                        .getBooleanExtra(IntentFlag.INTENT_FLAG_ACTION, false);
                if (isFinish) {
                    finish();
                }
                try {
                    Clazz clazz = (Clazz) data
                            .getSerializableExtra(IntentFlag.INTENT_FLAG_OBJ);
                    if (tvSelectClass != null) {
                        tvSelectClass.setText(clazz.getClassName());
                    }
                    mHomeWorkData.setClazz(clazz);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /*
     * 重新写答题卡编码
     */
    private void showAddCodeDialog(boolean showSelectClass, String className) {
        final CWDialog mAddCodeDialog = new CWDialog(this, false, false);
        mAddCodeDialog.setOnDismissListener(this);
        stopCamera();
        mScanHandler.doBatchHomeWorkEnd();
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_exam_code,
                null);
        final EditText editText = (EditText) view
                .findViewById(R.id.dialog_exam_code_et);
        tvSelectClass = (TextView) view.findViewById(R.id.tv_select_class);
        final TextView tvTestPaperName = (TextView) view
                .findViewById(R.id.tv_test_paper_name);
        TextPaperEditChangedListener textPaperEditChangedListener = new TextPaperEditChangedListener();
        textPaperEditChangedListener.setActionResultListener(
                new TextPaperEditChangedListener.ActionResultListener() {
                    @Override
                    public void onAction(int actionCode, String info) {
                        if (actionCode == TextPaperEditChangedListener.ActionCode.READY_REQUEST) {
                            editText.setEnabled(false);
                            editText.clearFocus();
                        } else {
                            editText.setEnabled(true);
                            if (actionCode == TextPaperEditChangedListener.ActionCode.RESULT_SUCCESS
                                    || actionCode == TextPaperEditChangedListener.ActionCode.MODIFYING) {
                                tvTestPaperName.setText(info);
                                mHomeWorkData.setTextPaperName(info);
                            } else if (actionCode == TextPaperEditChangedListener.ActionCode.RESULT_ERROR) {
                                CWToast.makeText(CaptureActivity.this, info,
                                        Toast.LENGTH_LONG, true)
                                        .setToastType(CWToast.TOAST_TYPE_ERROR)
                                        .show();
                            }
                        }
                    }
                });
        editText.addTextChangedListener(textPaperEditChangedListener);
        ScanHandler.HomeWorkData homeWorkData = mHomeWorkData;

        if (homeWorkData.getCodeId() != 0) {
            editText.setText(homeWorkData.getCodeId() + "");
        }
        String cclassName = null;
        cclassName = homeWorkData.getClazz().getClassName();
        if (TextUtils.isEmpty(cclassName)) {
            cclassName = className;
        }
        tvSelectClass.setText(cclassName);
        if (!showSelectClass) {
            view.findViewById(R.id.ll_select_class).setVisibility(View.GONE);
        }
        mAddCodeDialog.setCancelable(true);
        mAddCodeDialog
                .setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        mGalleyTab.setSelection(0);
                    }
                });
        mAddCodeDialog.setContentView(view);
        mAddCodeDialog.setPositiveButton(R.string.confirm,
                new android.content.DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        String code = editText.getText().toString().trim();

                        if (TextUtils.isEmpty(code) || code.length() < 9) {
                            // mGalleyTab.setSelection(0);
                            CWToast.makeText(CaptureActivity.this,
                                    R.string.ansercard_code_must_not_empty,
                                    Toast.LENGTH_LONG, true)
                                    .setToastType(CWToast.TOAST_TYPE_ALERT)
                                    .show();
                            return;
                        }
                        if (TextUtils.isEmpty(tvSelectClass.getText())) {
                            CWToast.makeText(CaptureActivity.this,
                                    R.string.class_is_not_select,
                                    Toast.LENGTH_LONG, true)
                                    .setToastType(CWToast.TOAST_TYPE_ALERT)
                                    .show();
                            return;
                        }
                        if (TextUtils.isEmpty(tvTestPaperName.getText())) {
                            CWToast.makeText(CaptureActivity.this,
                                    R.string.test_paper_name_must_not_empty,
                                    Toast.LENGTH_LONG, true)
                                    .setToastType(CWToast.TOAST_TYPE_ALERT)
                                    .show();
                            return;
                        }
                        mAddCodeDialog.dismiss();
                        ScanHandler.HomeWorkData homeWorkData = mHomeWorkData;
                        homeWorkData.setCodeId(Long.valueOf(code));
                        startCheckTip(SCAN_NOT_FOUND_TIME);
                    }
                }, false);
        mAddCodeDialog.setNegativeButton(R.string.cancel,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mGalleyTab.setSelection(0);
                        mTvTitle.setText(R.string.sao_qrcode);
                    }
                });
        mAddCodeDialog.show();
        tvSelectClass.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                InputMethodManager inputmanger = (InputMethodManager) getSystemService(
                        Context.INPUT_METHOD_SERVICE);
                inputmanger.hideSoftInputFromWindow(
                        tvSelectClass.getWindowToken(), 0);
                SerializableManager.getInstance().deSerialize(
                        SerializableManager.SerializeKey.SHARE_KEY_CLASS_LIST,
                        new BaseCallBack() {


                            @Override
                            public void failed(int errorCode, Object data) {

                            }

                            @Override
                            public void failed(Object data) {

                            }

                            @Override
                            public void success(Object data) {
                                List<SelectObject> selectObjects = (List<SelectObject>) data;
                                ScanJumpManager.jumpToSelectObjectDialog(0,
                                        CaptureActivity.this, 0, selectObjects,
                                        mHomeWorkData.getClazz());
                            }
                        });

            }
        });
    }

    public void stopCamera() {
        try {
            mViewfinderView.stopScanAnim();
            mCameraManager.getCamera().stopPreview();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void startCamera() {
        try {
            mCameraManager.getCamera().startPreview();
            if (mHandler != null) {
                mHandler.sendEmptyMessage(R.id.auto_focus);
            }
            if (mCameraManager
                    .getCurrentCaptureMode() != CameraManager.CaptureMode.ANSWERCARD) {
                mViewfinderView.startScanAnim();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onDismiss(DialogInterface dialog) {
        startCamera();
        if (mGalleyTab.getSelectedItemPosition() == 1) {
            mGalleyTab.setSelection(1);
        }
    }
}
